package com.carey.blog.tencent.microblog.oauth;

import com.carey.blog.framework.latke.repository.Transaction;
import com.carey.blog.libs.qweibo.OauthKey;
import com.carey.blog.libs.qweibo.QWeiboSyncApi;
import com.carey.blog.libs.qweibo.QWeiboType.PageFlag;
import com.carey.blog.libs.qweibo.QWeiboType.ResultType;
import com.carey.blog.model.Preference;
import com.carey.blog.repository.impl.PreferenceGAERepository;
import com.carey.blog.util.Preferences;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

/**
 * OAuth callback.
 * 
 */
public final class Callback extends HttpServlet {

	/**
	 * Default serial version uid.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger.getLogger(Callback.class
			.getName());
	/**
	 * Preference utilities.
	 */
	private Preferences preferenceUtils = Preferences.getInstance();

	@Override
	protected void doGet(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException,
			IOException {
		LOGGER.fine("Tencent microblog OAuth allback....");

		final JSONObject preference = preferenceUtils.getPreference();
		String appKey = null;
		String appSecret = null;
		String tokenSecret = null;
		try {
			appKey = preference.getString(Preference.TENCENT_MICROBLOG_APP_KEY);
			appSecret = preference
					.getString(Preference.TENCENT_MICROBLOG_APP_SECRET);
			tokenSecret = preference
					.getString(Preference.TENCENT_MICROBLOG_TOKEN_SECRET);
		} catch (final Exception e) {
			LOGGER.log(Level.SEVERE, e.getMessage(), e);

			return;
		}

		final String tokenKey = request.getParameter("oauth_token");
		final String verifier = request.getParameter("oauth_verifier");

		final QWeiboSyncApi api = new QWeiboSyncApi();
		final String resp = api.getAccessToken(appKey, appSecret, tokenKey,
				tokenSecret, verifier);
		final OauthKey oauthKey = AuthorizeToken.parseToken(resp);

		final Transaction transaction = PreferenceGAERepository.getInstance()
				.beginTransaction();
		try {
			preference.put(Preference.TENCENT_MICROBLOG_APP_KEY, appKey);
			preference.put(Preference.TENCENT_MICROBLOG_APP_SECRET, appSecret);
			preference.put(Preference.TENCENT_MICROBLOG_TOKEN_KEY,
					oauthKey.tokenKey);
			preference.put(Preference.TENCENT_MICROBLOG_TOKEN_SECRET,
					oauthKey.tokenSecret);

			preferenceUtils.setPreference(preference);
			transaction.commit();
		} catch (final Exception e) {
			if (transaction.isActive()) {
				transaction.rollback();
			}
			LOGGER.log(Level.SEVERE, e.getMessage(), e);

			return;
		}

		final String homeMsg = api.getHomeMsg(appKey, appSecret,
				oauthKey.tokenKey, oauthKey.tokenSecret,
				ResultType.ResultType_Json, PageFlag.PageFlag_First, 20);
		LOGGER.finer(homeMsg);

		response.sendRedirect("/admin-index.do");
	}
}
